// pages/search/search.js
Page({
  data: {
    searchQuery: '',       // 用户输入的搜索关键词或传递的关键词
    searchHistory: [],     // 搜索历史数组
    results: []            // 搜索结果数组
  },

  onLoad: function(options) {
    const query = options.keyword ? decodeURIComponent(options.keyword) : '';
    this.setData({
      searchQuery: query // 设置传递过来的关键词
    });

    if (query) {
      console.log('触发搜索，传递的关键词：', query);
      this.performSearch(query);
      this.updateSearchHistory(query);
    }

    this.loadSearchHistory(); // 加载搜索历史
  },

  loadSearchHistory: function() {
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({
      searchHistory: history
    });
  },

  onSearchInput: function(e) {
    this.setData({
      searchQuery: e.detail.value // 更新搜索关键词
    });
  },

  onSearch: function() {
    const query = this.data.searchQuery.trim();
    if (query === '') {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      });
      return;
    }

    console.log('点击搜索按钮，关键词：', query);
    this.performSearch(query);
    this.updateSearchHistory(query);
  },

  performSearch: function(query) {
    console.log('执行搜索，关键词：', query);
    const db = wx.cloud.database();
    if (!db) {
      console.error('数据库未正确初始化');
      return;
    }

    db.collection('products')
      .where({
        name: db.RegExp({
          regexp: query,
          options: 'i' // 不区分大小写
        })
      })
      .get({
        success: res => {
          console.log('搜索结果：', res.data);
          this.setData({
            results: res.data
          });
        },
        fail: err => {
          wx.showToast({
            title: '搜索失败',
            icon: 'none'
          });
          console.error('搜索失败', err);
        }
      });
  },

  updateSearchHistory: function(query) {
    let history = this.data.searchHistory;
    history = history.filter(item => item !== query);
    history.unshift(query);
    if (history.length > 10) {
      history = history.slice(0, 10);
    }
    this.setData({
      searchHistory: history
    });
    wx.setStorageSync('searchHistory', history);
  },

  onHistoryTap: function(e) {
    const query = e.currentTarget.dataset.item;
    console.log('点击历史搜索关键词：', query);

    this.setData({
      searchQuery: query
    });

    console.log('执行搜索，历史记录的关键词：', query);
    this.performSearch(query); // 自动触发搜索
  },

  clearHistory: function() {
    this.setData({
      searchHistory: []
    });
    wx.removeStorageSync('searchHistory');
  },

  viewProduct: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/productDetail/productDetail?id=${id}`
    });
  }
});